import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login/index.vue'
import Home from '../views/home/home.vue'
import ArticleList from '../views/articles/index'
import Comment from '../views/comment/index'
import Fans from '../views/fans/index'
import Main from '../views/main/index'
import Image from '../views/image/index'
import NouFound from '../views/notFound/index'
import AddArticle from '../views/articles/addArticle'
import EditArticle from '../views/articles/editArticle'

import {getUserToken} from '@/store/index.js'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    children:[
      {
        path: '/articleList',
        name: 'ArticleList',
        component: ArticleList
      },
      {
        path: '/comment',
        name: 'Comment',
        component: Comment
      },
      {
        path: '/fans',
        name: 'Fans',
        component: Fans
      },
      {
        path: '/main',
        name: 'Main',
        component: Main
      },
      {
        path: '/image',
        name: 'Image',
        component: Image
      },
      {
        path: '/setting',
        name: 'Setting',
        component: ()=> import(/* webpackChunkName: "setting" */ '../views/setting/index.vue' )
      },
      {
        path: '/addArticle',
        name: 'AddArticle',
        component: AddArticle
      },
      {
        path: '/editArticle',
        name: 'EditArticle',
        component: EditArticle
      },
      {
        path: '/notFound',
        name: 'NouFound',
        component: NouFound
      },
    ]
  },
  {
    path: '*',
    component: NouFound
  },
  
  
]

const router = new VueRouter({
  routes
})

router.beforeEach((to,from,next)=>{
  console.log("to",to)
  if(to.path === '/' || to.path === '/main'){
    const userInfo = getUserToken()
    if(userInfo && userInfo.token){
      next()
    }else{
      console.log("##########")
      router.replace('/login');
    }
  }else{
    next()
  }
  
})

    const originalPush = VueRouter.prototype.push
    VueRouter.prototype.push = function push(location) {
      return originalPush.call(this, location).catch(err => err)
    }

export default router
